<?php

include('pagina.php');
include('database.php');
include('auth.php');
include('core.php');

// Verifica se esta autenticado com pelo menos nivel 1
validaPermissao(1);

// Inicia cabecalho da pagina
pagina_inicio('ParkSys - Message book');
adicionar_css('msgbook.css');
pagina_head();

// Mostra opcoes
echo "<ul id=opcoes>";
echo "<li><a href='msgbook.php?",
	(isset($_GET['page'])? "&amp;page={$_GET['page']}" : ""),
	"&amp;print=1' target='_blank'><img src='img/print.png' alt=''>Print</a></li>";
echo "</ul><br><br>";

echo "<form id=new_message class=big_form method=POST action='msgbook.php'>";
echo "<label for=message>Leave your message:</label><br><textarea id=message name=message cols=80 rows=5 maxlength=255>";
echo "</textarea><br>";
if (nivelAutenticado() >= 3)
    echo "<label for=show_home>Show message in home page</label> <input type=CHECKBOX name=show_home id=show_home> ";
echo "<input type=SUBMIT name=submit value='Submit'>";
echo "</form>";

// Verifica se houve envio do formulario.
if (isset($_POST['submit']))
{
	// Nova mensagem
	if (isset($_POST['message']))
	{
		query_bd("INSERT INTO messages VALUES " .
                 "(NULL, {$_SESSION[site_id]['id']}, NULL, " . (isset($_POST['show_home'])? "TRUE" : "FALSE") . ", '" .
                 $_POST['message'] . "')");
	}
}

// Verifica se ha tentativa de deletar uma mensagem
if (isset($_GET['delete']))
{
	$message = query_fetch("SELECT * FROM messages WHERE id={$_GET['delete']}");
	if (nivelAutenticado() >= 3 || $_SESSION[site_id]['id'] == $message['employee_id'])
	{
		query_bd("DELETE FROM messages WHERE id={$_GET['delete']}");
	}
}

$page = (isset($_GET['page'])? $_GET['page'] : 0);

$resultado = query_bd("SELECT * FROM messages ORDER BY posted DESC LIMIT " .
	($page * MESSAGES_PER_PAGE) . ", " . MESSAGES_PER_PAGE);

if (!isset($_GET['print']))
{
	echo "<div id=navegador>";
	if ($page > 0)
		echo "<a href='msgbook.php?page=", ($page-1), "'>&lt recent</a> ";
	if (mysql_affected_rows() == MESSAGES_PER_PAGE)
		echo "<a href='msgbook.php?page=", ($page+1), "'>older &gt;</a>";
	echo "</div>";
}

echo "<table id=messages>";
echo "<caption><em>Message Book</em></caption>";

while ($message = mysql_fetch_array($resultado))
{
	flush();	/* Manda o que ja tem em buffer para o cliente */

	echo "<tr>";

	$dono_da_mensagem = (nivelAutenticado() >= 3 || $_SESSION[site_id]['id'] == $message['employee_id']);

	echo "<td class=first>",
	($message['employee_id'] != 0 && $dono_da_mensagem? 
        "<a href='employee.php?id={$message['employee_id']}'>" : "");

    /* Gets user name */	
	$contact = ($message['employee_id'] == 0? Array('name'=>'Admin') :
                query_fetch("SELECT contacts.name FROM contacts, employees WHERE " .
                "employees.contact_id=contacts.id AND employees.id={$message['employee_id']}"));

	if (!isset($_GET['print']))
	{
        /* if message from admin, shows system logo */
        if ($message['employee_id'] == 0)
        {
            echo "<img class=employee_picture src='img/icone.png' alt='Admin'>";
        }
        else
        {
            $empl_picture = query_fetch("SELECT has_picture FROM employees WHERE id={$message['employee_id']} LIMIT 1");

            echo "<img class=employee_picture src='",
                ($empl_picture['has_picture']? "portrails/{$message['employee_id']}_thumb.jpg" : "portrails/unknown_thumb.png"),
                "' alt=''>";
        }
        echo "<br>";
	}
	echo "<p>{$contact['name']}</p>", 
         ($message['employee_id'] != 0 && $dono_da_mensagem? "</a>" : "");

	echo "<td class=second><p>", nl2br(htmlspecialchars(strip_tags($message['content']))), "</p>";
	echo "<small>posted in ", $message['posted'], "</small>";

	if ($dono_da_mensagem && !isset($_GET['print']))
	{
		echo "<br><small><a href='msgbook.php?delete=${message['id']}'>delete</a></small>";
	}
}

echo "</table>";

// Finaliza pagina
pagina_fim();

?>
